﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_SaleOrder_RicePeriod : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dtpFromDate.SelectedDate = DateTime.Now;
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
       
        int PageNumber = 1;
        int PageSize = gv.PageSize;
        DataTable dt = LoadData(PageNumber, PageSize);
        if (dt.Rows.Count > 0)
        {
            gv.DataSource = dt;
            gv.ClientSettings.Scrolling.AllowScroll = true;
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"].ToString());
            
        }
        else {
            gv.DataSource = new DataTable();
        }
        gv.DataBind();
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        BindData();
       // gv.DataBind();
    }
    private void BindData()
    {
        gv.Visible = true;
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;
        DataTable dt = LoadData(PageNumber, PageSize);
        if (dt.Rows.Count > 0)
        {
            gv.ClientSettings.Scrolling.AllowScroll = true;
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"].ToString());
            gv.DataSource = dt;
        }
        else
        {
            gv.DataSource = new DataTable();

        }
    }
    protected void gv_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                String ListPara = e.CommandArgument.ToString();//Lay ID 
                //helper = new DatabaseHelper();
                string[] arr = ListPara.Split('@');

                if (commandName == "UpdateItem")
                {
                    try
                    {
                        DBDataContext  db = new DBDataContext();
                        var objSelect = db.PeriodRices.FirstOrDefault(x => x.PreSaleOrderID == Convert.ToInt32(arr[0]));
                        var objUserID = db.Users.FirstOrDefault(x => x.UserName == Session["Username"].ToString());
                        if (objSelect == null)
                        {

                            PeriodRice objInsert = new PeriodRice();
                            objInsert.PreSaleOrderID = Convert.ToInt32(arr[0]);
                            objInsert.Period = Convert.ToDecimal(arr[4]);
                            objInsert.LastSaleOrderID = Convert.ToInt32(arr[2]);
                            objInsert.CustomerID = Convert.ToInt32(arr[1]);
                            objInsert.CalledUserID = Convert.ToInt32(objUserID.ID);
                            objInsert.UserName = Session["Username"].ToString();
                            objInsert.CreatedBy = Session["Username"].ToString();
                            objInsert.ExpectedDateTime = Convert.ToDateTime(arr[3]);
                            objInsert.CreatedDateTime = DateTime.Now;
                            objInsert.Status = 1;
                            db.Insert(objInsert);
                            db.SubmitChanges();
                            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật thành công!");
                            BindData();
                            gv.DataBind();
                        }
                        else
                        {
                            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Cập nhật không thành công. Bởi vì  khách hàng này đã gọi trước đó!");
                        }
                    }
                   
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("RicePeriod Page-gvData_ItemCommand-EditItem-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message);
                    }
                }
                
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("RicePeriod Page-gvData_ItemCommand-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message);
            }
        }
    }
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        ExportExcel();
    }
    protected void ExportExcel()
    {
        DataTable tblresult = LoadData(1, 60000);
        if (tblresult.Rows.Count > 0)
        {
            ExcelUtil.ExportDataTableToExcel2007FromRadGrid(tblresult, gv, "Chukymuagao");
        }
        else
        {
            JavascriptUtil.LoadMessage(Page, false, "Không có dữ liệu xuất Excel !!!");

        }
    }
    protected DataTable LoadData(int pageNumber, int pageSize)
    {
        DataTable tblResult = new DataTable();
        try
        {
            //DateTime FromDate;
            //if (dtpFromDate.SelectedDate == null)
            //{
            //    FromDate = DateTime.Parse("2014-01-01");
            //}
            //else
            //{
            //    FromDate = dtpFromDate.SelectedDate.Value;
            //}
            //DateTime ToDate;
            //if (dtpToDate.SelectedDate == null)
            //{
            //    ToDate = DateTime.Parse("2099-01-01");
            //}
            //else
            //{
            //    ToDate = dtpToDate.SelectedDate.Value;
            //}

            string FromDate = Utils.KillChars(this.dtpFromDate.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.dtpFromDate.SelectedDate));
            string ToDate = Utils.KillChars(this.dtpToDate.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.dtpToDate.SelectedDate));

            DatabaseHelper db = new DatabaseHelper();
            System.Data.Common.DbParameter paramCustomerName = db.Parameter;
            paramCustomerName.ParameterName = "CustomerName";
            paramCustomerName.DbType = DbType.String;
            paramCustomerName.Value = Utils.KillChars(txtCustomerName.Text.Trim());
            db.AddParameter(paramCustomerName);

            System.Data.Common.DbParameter paramCustomerCode= db.Parameter;
            paramCustomerCode.ParameterName = "CustomerCode";
            paramCustomerCode.DbType = DbType.String;
            paramCustomerCode.Value = Utils.KillChars(txtCustomerCode.Text.Trim());
            db.AddParameter(paramCustomerCode);

            System.Data.Common.DbParameter paramPhoneNumber = db.Parameter;
            paramPhoneNumber.ParameterName = "PhoneNumber";
            paramPhoneNumber.DbType = DbType.String;
            paramPhoneNumber.Value = Utils.KillChars(txtPhoneNumber.Text.Trim());
            db.AddParameter(paramPhoneNumber);

            System.Data.Common.DbParameter paramStatusCall = db.Parameter;
            paramStatusCall.ParameterName = "StatusCall";
            paramStatusCall.DbType = DbType.Int16;
            paramStatusCall.Value = Convert.ToInt16(Utils.KillChars(cboStatusCall.SelectedValue.Trim()));
            db.AddParameter(paramStatusCall);


            System.Data.Common.DbParameter paramStartDate = db.Parameter;
            paramStartDate.ParameterName = "FromDateTime";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = FromDate;
            db.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = db.Parameter;
            paramEndDate.ParameterName = "ToDateTime";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = ToDate;
            db.AddParameter(paramEndDate);


            System.Data.Common.DbParameter paramPageNumber = db.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = pageNumber;
            db.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = db.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = pageSize;
            db.AddParameter(paramPageSize);

            tblResult = db.ExecuteDataTable("GetRicePeriod", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            //int ProvinceID = int.Parse(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
            //DBDataContext db = LINQUtil.GetDBWriteOnly();
            //tblResult = db.Report_SaleEmployee(ProvinceID, int.Parse(this.cboShop.SelectedValue), int.Parse(this.cboEmployeeDeliveryCode.SelectedValue), FromDate, ToDate, pageSize, pageNumber).ToList().ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("RicePeriod-LoadData");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
        return tblResult;
    }
}